package com.xfi.liuliangjun.util.wechat;

import android.os.Handler;
import android.os.Looper;

import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2017/9/4.
 * 登录，分享回调页面
 */

public class BaseWXEntryActivity extends BaseWXActivity {

    //微信请求第三方应用回调
    @Override
    public void onReq(BaseReq baseReq) {

    }

    //微信响应第三方应用回调
    @Override
    public void onResp(BaseResp baseResp) {
        String code = ((SendAuth.Resp)baseResp).code;
        //获取access_token
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/sns/oauth2/access_token?")
                .append("appid=")
                .append(WeChatUtil.appid)
                .append("&secret=")
                .append(WeChatUtil.secret)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        HttpUtil.sendGetRequest(sb.toString(), new DataGetSuccessListener() {
            @Override
            public void dataGetSuccess(String date) {
                System.out.println("获取token----------->>>>>"+date);
                try {
                    JSONObject jsonObject = new JSONObject(date);
                    String access_token = jsonObject.getString("access_token");
                    String openid = jsonObject.getString("openid");
                    //获取用户信息
                    StringBuffer sb = new StringBuffer();
                    sb.append("https://api.weixin.qq.com/sns/userinfo?access_token=")
                            .append(access_token)
                            .append("&openid=")
                            .append(openid);
                    HttpUtil.sendGetRequest(sb.toString(), new DataGetSuccessListener() {
                        @Override
                        public void dataGetSuccess(final String date) {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    WeChatUtil.mListener.getUserInfo(date);
                                }
                            });
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        finish();
    }
}
